package cn.kinoko.exception;

import cn.kinoko.common.base.exception.BaseExceptionAdvice;
import cn.kinoko.common.base.model.Result;
import cn.kinoko.common.code.ErrorCodeEnum;
import cn.kinoko.common.utils.ExceptionUtil;
import com.alibaba.fastjson.JSON;
import feign.FeignException;
import feign.RetryableException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * @author kinoko
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionAdvice extends BaseExceptionAdvice {
    /**
     * 业务异常
     * @param e 异常
     * @return 错误信息
     */
    @ExceptionHandler(ExceptionUtil.BizException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> bizExceptionHandler(ExceptionUtil.BizException e) {
        log.error("[业务异常]{}", e.getMessage(), e);
        return e.getErrorCodeEnum() == null ? Result.error(e.getMessage()) : Result.error(e.getErrorCodeEnum());
    }

    /**
     * 未找到处理器异常
     * @param e 异常
     * @return 错误信息
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Result<Object> maxUploadSizeExceededExceptionHandler(MaxUploadSizeExceededException e) {
        log.error("[超出上传文件大小异常]" + e.getMessage(), e);
        return Result.error(ErrorCodeEnum.USER_ERROR_A0702);
    }

    /**
     * 远程调用异常
     * @param e 异常
     * @return 错误信息
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({RetryableException.class, FeignException.class})
    public Result<Object> feignExceptionHandler(FeignException e) {
        log.error("[远程调用异常]{}", e.getMessage());
        // 获取响应体
        String body = e.contentUTF8();
        Result<Object> result = JSON.parseObject(body, Result.class);
        // 无法转化常规格式的先初始化再返回
        if (result == null || StringUtils.isBlank(result.getCode())) {
            return Result.error(ErrorCodeEnum.SERVICE_ERROR_C0001);
        }
        return result;
    }
}
